// This file contains the boilerplate to execute your React app.
// If you want to modify your application's content, start in "index.js"

import './process'
import {
  ReactInstance
} from 'react-360-web';
import qs from 'qs'

import AutoCameraController from './CameraController/AutoCameraController'
import LoaderModule from './modules/LoaderModule'
import ThumbnailsModule from './modules/ThumbnailsModule'

function init(bundle, parent, options = {}) {

  const params = qs.parse(location.search.split('?')[1])
  console.log(params)
  let thumbnails = params.thumbnails || 'default'

  fetch(params.source)
    .then(response => response.json())
    .then(data => {
      const photos = data.scenes.map(scene => {
        return {
          // uri: this.asset(scene.photopanos[0].src)
          uri: scene.photopanos[0].src,
          format: '2D'
        }
      })


      const uiContainer = document.createElement('div')
      uiContainer.className = 'vslider-ui-container'
      // uiContainer.style = 'position: absolute; top: 0; left: 0; width: 100%; height: 100%'

      // const thumbnailsModule = new ThumbnailsModule(uiContainer)

      const r360 = new ReactInstance(bundle, parent, {
        // Add custom options here
        fullScreen: true,
        nativeModules: [
          ctx => new ThumbnailsModule(uiContainer, ctx, thumbnails),
          ctx => new LoaderModule(uiContainer)
        ],
        ...options,
      });

      // Render your app content to the default cylinder surface
      r360.renderToSurface(
        r360.createRoot('Slideshow', {
          photos,
          thumbnails: true,
          navigation: false,
          interval: params.interval || 6000
        }),
        r360.getDefaultSurface()
      );

      // Load the initial environment
      // r360.compositor.setBackground(r360.getAssetURL('360_world.jpg'));
      window.addEventListener('hashchange', (e) => {
        // r360.compositor.setBackground(r360.getAssetURL('360_world.jpg'))
        console.log('hashchange', e)
      }, false)

      const speed = params.speed === undefined ? 0.05 : parseFloat(params.speed)
      // console.log('speed', speed, params)
      const cam = new AutoCameraController(r360._eventLayer, speed)
      r360.controls.addCameraController(cam)

      // console.log(r360)
      r360._parent.appendChild(uiContainer)
    })
}

window.React360 = {init};
